// pages/index/index.js
var App = getApp();
let locateStr = '';//定位信息
let boxId = '';//盒子id
let showList = [];
let canGOSupply = false; //是否点击过跳转按钮
Page({

  /**
   * 页面的初始数据
   */
  data: {
    topHide:false,// 顶部是否隐藏
    locate:'',//定位
    inviteId:'', //邀请id
    hasPhone: false, //是否有手机号
    noNetwork: false, //是否有网络
    navList:[
      { name: '零食盒子', path: '/pages/index/index'},
      { name: '零食直购', path: '/pages/index/mall/mall'},
      { name: '精选商城', path: App.data.globalMall}
    ],
    currentPage:0, //当前导航的位置
    imgUrls: [],
    indicatorDots: false,
    autoplay: true,
    currentIndex: 0, //banner当前位置
    imgPreMargin: '', //banner前面露出的部分
    imgNextMargin: '', //banner后面露出的部分
    hostelName:'', //宿舍信息
    isManager:true, //是否是管理员
    managerTip:'酸奶特价啦~快来囤货吧！', //补货提示语
    goodsList:[],
    boxStatus: -1, //盒子状态，0申领盒子,1管理员未补货，2管理员盒子待确认，待出库2.53管理员补货配送中，4消费，5有消费记录还未申领盒子
    isMyBox: false, //是否在我的盒子
    totalMoney: '0.00',//购物车总金额
    totalNum: 0, //商品数量
    hoverAlert: false,//购物车列表
    shoppingCart: [],
    newPersonActive:false, //是否有新人活动
    userIsvip: false, //用户是否是vip
    originTotal: '0.00', //订单原价总和
    vipSave: '0.00', //vip节省
    activeSave: '0.00', //活动节省
    totalSave:'0.00', //总共节省的价钱
    cartActiveMsg:'', //购物车活动广告
    currentType: 0 ,//列表显示的类型
    newPersonAd: '',
    everyLoginImg:'', //每日登录提示
    everyLogin: false,
    showGuideIntro: false, //显示消费指引
    noGoods: false,
    versionContent:'', // 强制更新版本背景图片
    isTipSupply: false, //提醒补货 
    moreGuideAlert: false, //更多蒙层引导
    showConfirm: false //是否弹出确认收货弹窗
  }, 

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
    })    
    this.updateVersion(); //强制更新版本信息

    //扫码进来
    if (options.q) {
      let qrUrl = decodeURIComponent(options.q);//获取二维码的携带的链接信息
      if (qrUrl.indexOf('boxId') > -1) {
        options.boxId = qrUrl.split('=')[1];
        boxId = options.boxId;
      }
      if (qrUrl.indexOf('invite_id') > -1 || qrUrl.indexOf('invite') > -1) { //邀请新用户
        options.invite = qrUrl.split('=')[1];
        this.setData({
          inviteId: options.invite
        })
      }
    } else if (options.boxId != undefined) {//应用内扫一扫
      boxId = options.boxId;
    } else if (options.invite != undefined) {
      this.setData({
        inviteId: options.invite
      })
    }else {
      boxId = 'none';//没有boxId传入
    }

    // 加载数据
    if (wx.getStorageSync('token') == '') { //无token信息
      this.getWxUserinfo();
    } else {
      if (wx.getStorageSync('currentSchool') == '') {
        this.autoLocation();//自动定位
        this.getTokenLogin();
      } else {
        this.setData({
          locate: wx.getStorageSync('currentSchool')
        })
        let msg = wx.getStorageSync('allUserMsg');
        if ((msg.first_supply.order_status != '3' && msg.userinfo.havebox == 1) || msg.userinfo.hostel_id == null || (msg.first_supply.order_status != 'null' && msg.userinfo.havebox == 0)){
          this.getTokenLogin();
        }else{
          this.getButtonStatus();
        }
      }
    }
  },

  //用户状态判断
  getButtonStatus:function(){
    this.getBanner(); 
    let allMsg = wx.getStorageSync('allUserMsg');
    if( boxId == 'none'){ //没有boxid传入，取用户信息
      boxId = allMsg.last_order.box_id != null ? allMsg.last_order.box_id : (allMsg.box.box_id == null ? '' : allMsg.box.box_id)
    }
    
    let schoolAddress = allMsg.first_supply.address == null ? '' : allMsg.first_supply.address[0] + allMsg.first_supply.address[1] + '-' + allMsg.first_supply.address[2] + (allMsg.first_supply.address[3] == undefined ? '' : ('-' + allMsg.first_supply.address[3]));
    let myBox = false; //是否在自己盒子
    let status = 0;
    //判断是否是盒子管理员
    this.setData({
      isManager: allMsg.userinfo.havebox == 1 ? true : false
    })

    if( boxId=='' ){ //没有盒子id三种状态，未申领，已申领未补货，已补货未确认
      myBox = true;
      if (allMsg.userinfo.hostel_id == null) { //未申领
        status = 0;
      } else { 
        if (allMsg.first_supply.order_status=='0'){ // 已补货未确认
          status = 2;
          this.setData({
            hostelName: schoolAddress
          })
        }else{
          status = 1; //已申领未补货
        }
      }
      
    } else if (boxId != allMsg.box.box_id){ //不在自己盒子内
      myBox = false;  
      if (allMsg.userinfo.hostel_id == null) { //别人盒子，自己未申领
        status = 5; 
        this.setData({
          managerTip: '老在别人的盒子消费，也去申领个自己的盒子吧！'
        })
      } else {
        status = 4; 
        this.setData({
          managerTip: '您目前在别人盒子消费中，点击前往我的盒子'
        })
      }
      this.getBoxAddress(); //获取宿舍地址
    }else{ //在自己盒子里
      myBox = true;
      var first_order = allMsg.first_supply.order_status; //首单状态

      if (this.data.isManager) { //管理员
        switch (first_order){
          case 'null':   //未补货
            status = 1; 
            break;
          case '0': //未确认
            status = 2;
            this.setData({
              hostelName: schoolAddress
            })
            break;
          case '1': //待出库
            status = 2.5;
            this.setData({
              hostelName: schoolAddress
            })
            break;
          case '2': //配送中
          case '11': //配送中
            status = 3;
            this.setData({
              hostelName: allMsg.first_supply.address[0] + allMsg.first_supply.address[1] + allMsg.first_supply.address[2]
            })
            break;
          case '3': //已完成
            status = 4;
            if (allMsg.box.is_supply){
              this.setData({
                managerTip: '余量不足，管理员快去补货吧。'
              })
            }else{
              this.setData({
                managerTip: '您是盒子管理员，点击这里前往补货。'
              })
            }
            this.getBoxAddress(); //获取宿舍地址
            this.supplyAdMsg();//获取补货广告提示
            break;
          case '4':  //已取消
            status = 1;
            break;
          default: 
        }
      }else if (allMsg.userinfo.hostel_id != null) { //普通用户
        status = 4;
        this.setData({
          managerTip: '如果货品不足，可以联系管理员补货'
        })
        this.getBoxAddress(); //获取宿舍地址
      } else { //游客
        status = 0;
      }
    }
    this.setData({
      isMyBox: myBox,
      boxStatus: status,
      userIsvip: wx.getStorageSync('allUserMsg').vip.is_vip
    }) 
    
  },

  //获取宿舍地址
  getBoxAddress: function () {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/users/login/getaddress', //接口地址
      data: {
        token: wx.getStorageSync('token'),
        box_id: boxId,
      },
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function (res) {
        if (res.data.error == 0) {
          that.setData({
            hostelName: res.data.data.address
          })
          that.getBoxGoodsList();//获取消费列表
          that.getOrderCount();//获取用户订单统计
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },

  //获取用户订单统计
  getOrderCount: function () {
    let that = this;
    let allMsg = wx.getStorageSync('allUserMsg');
    wx.request({
      url: App.data.globalAPI + '/users/user/ordercount', 
      data: {
        token: wx.getStorageSync('token'),
      },
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function (res) {
        if (res.data.error == 0) {
          if (parseInt(res.data.data.supply) < 3 && allMsg.box.is_supply){//需要补货，且补货次数未满3次
            that.setData({
              isTipSupply: true
            })
          }else{
            that.setData({
              isTipSupply: false
            })
          }
          //消费满三次
          if (parseInt(res.data.data.expense) >= 3 && wx.getStorageSync('checkShowMore')==true){ //消费满三次
            if (wx.getStorageSync('moreGuide')!=true){
              that.setData({
                moreGuideAlert: true
              })
              wx.setStorageSync('moreGuide', true)
            }  
          }else{
            wx.setStorageSync('checkShowMore', false)
            that.setData({
              moreGuideAlert: false
            })
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log(wx.getSystemInfoSync().windowWidth)
    console.log(wx.getSystemInfoSync().windowHeight)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      locate: wx.getStorageSync('currentSchool') == '' ? '定位失败' : wx.getStorageSync('currentSchool'),
      currentIndex: 0
    })
    canGOSupply = false;//是否点击过补货
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  //页面滚动事件
  onPageScroll: function (e) {
    var scroll_top = e.scrollTop;
    if (scroll_top > 40){
      this.setData({
        topHide:true
      })
    }
    else{
      this.setData({
        topHide: false
      })
    }
  },


  //获取用户的openid
  getWxUserinfo: function () {
    const that = this;
    wx.login({
      success: function (res) {
        //发送请求
        wx.request({
          url: App.data.globalAPI + '/users/weixin/login', //接口地址
          data: {
            code: res.code,
            source: 'small program',//注册来源标识
            invite_id: that.data.inviteId//邀请人标识
          },
          header: {
            'content-type': 'application/json' //默认值
          },
          success: function (res) {
            console.log('成功inviteId=' + that.data.inviteId);
            if (res.data.error == 0) {
              wx.setStorageSync('token', res.data.data.token);
              
              //新用户活动判断
              if (wx.getStorageSync('allUserMsg') == '' && res.data.data.userinfo.hostel_id == null && res.data.data.last_order.box_id == null) {
                console.log('1023')
                that.setData({
                  newPersonActive: true 
                })
                that.newPersonImg();//新人活动图片
              } else {
                that.setData({
                  newPersonActive: false
                })
              }
             
              wx.setStorageSync('userInfo', res.data.data.userinfo);
              wx.setStorageSync('allUserMsg', res.data.data);

              that.everyLoginHandle(); //每天登录提醒
              that.getButtonStatus();//按钮状态判断
              that.autoLocation();

              let userMsg = wx.getStorageSync('userInfo');
              //用户是否绑定过手机号
              if (userMsg.phone == '0' || userMsg.phone == 0) {
                that.setData({
                  hasPhone: false
                })
              } else {
                that.setData({
                  hasPhone: true
                })
              }

              //游客判断是否可以绑定盒子管理员
              if (boxId != '') {
                if (userMsg.hostel_id == 'null' || userMsg.hostel_id == null) {
                  that.bindBoxManager(boxId);
                }
              }
            } else if (JSON.stringify(res.data.data) == "{}") {
              wx.hideLoading();
              that.setData({
                noNetwork: true
              })
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'none'
              })
            }
          },
          fail(res) {
            wx.hideLoading();
            that.setData({//无网络
              noNetwork: true
            })
          }
        })
      }
    })
  },

  //token登录
  getTokenLogin: function () {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/users/login/login', //接口地址
      data: {
        token: wx.getStorageSync('token'),
        source: 'small program',//注册来源标识
        phone_model: wx.getSystemInfoSync().model + ',' + wx.getSystemInfoSync().brand//设备型号
      },
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function (res) {
        if (res.data.error == 0) {
          that.setData({
            noNetwork: false,
            hasNewMsg: res.data.data.new_msg
          })
          wx.setStorageSync('token', res.data.data.token);
          wx.setStorageSync('userInfo', res.data.data.userinfo);
          wx.setStorageSync('allUserMsg', res.data.data);
          wx.setStorageSync('allUserMsg', res.data.data);
          wx.setStorageSync('checkShowMore', true)

          that.everyLoginHandle(); //每天登录提醒
          
          let storage = wx.getStorageSync('allUserMsg');
          let userMsg = wx.getStorageSync('userInfo');
          if (userMsg.phone == '0' || userMsg.phone == 0) {//没有手机号
            that.setData({
              hasPhone: false
            })
          } else {
            that.setData({
              hasPhone: true
            })
          }
          if (storage.first_supply.order_status != '3' && storage.first_supply.order_status != null) {
            that.queryTheFirst(); //检查首单状态
          }else{
            that.getButtonStatus();//按钮状态判断
          }
        }
        else {
          that.getWxUserinfo();
        }
      }, fail() {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
        that.setData({
          noNetwork: true
        })
      }
    })
  },

  //查询首单状态
  queryTheFirst: function () {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/users/user/firstsupply',
      data: {
        token: wx.getStorageSync('token'),
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        let msg = wx.getStorageSync('allUserMsg');
        if (res.data.error == 0) {
          msg.first_supply = res.data.data;
          wx.setStorageSync('allUserMsg', msg)
          that.getButtonStatus();//按钮状态判断
        }
      }
    })
  },

  // 自动定位
  autoLocation: function () {
    const that = this;
    wx.getSetting({
      success(res) {
        if (typeof (res.authSetting['scope.userLocation']) == 'undefined' || res.authSetting['scope.userLocation']) {//没有授权信息
          wx.getLocation({
            type: 'wgs84',
            success(res) {
              const latitude = res.latitude //纬度
              const longitude = res.longitude //经度
              const accuracy = res.accuracy;
              
              // const latitude = '30.318765' //武汉
              // const longitude = '114.049287' //经度
              // const latitude = '39.90' //河北科大
              // const longitude = '116.40' //经度
              locateStr = longitude + ',' + latitude;//经度在前，纬度在后

              wx.setStorageSync('location', locateStr)
              wx.setStorageSync('latitude', latitude);
              wx.setStorageSync('longitude', longitude);
              that.getUserCity();//定位城市
              wx.hideLoading();
            },fail(){
              wx.showToast({
                icon: 'none',
                title: '定位失败，请手动开启'
              })
              that.setData({
                locate: '定位失败'
              })
            }
          })
        } else if (!res.authSetting['scope.userLocation']) {//授权被拒
          wx.showModal({
            title: '提示',
            content: '定位关闭，是否开启定位？',
            success (res) {
              if (res.confirm){
                wx.openSetting({
                  success(res) {
                    if (res.authSetting['scope.userLocation']){
                      that.autoLocation();
                    }else{
                      that.setData({
                        locate: '定位失败'
                      })
                    }                  
                  }
                })
              }else{
                wx.showToast({
                  icon:'none',
                  title: '定位失败，请手动开启'
                })
                that.setData({
                  locate: '定位失败'
                })
                // setTimeout(function(){
                //   wx.navigateTo({
                //     url: '/pages/index/location/adress',
                //   })
                // },600)
 
              } 
            }
          })
          wx.hideLoading();
        }
      }
    })

  },

  getUserCity: function ( ) {
    let that = this;
    
    wx.request({
      url: App.data.globalAPI + '/search/index/nearestschool',
      data: {
        token: wx.getStorageSync('token'),
        location: locateStr, 
        type: 'gps'
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res2) {
        const nearest = res2.data.data.nearest;
        const floors = res2.data.data.floors;
        if (res2.data.error == 0) {
          that.setData({
            locate: nearest.name == null ? '无法查到您的学校，请手动选择' : nearest.name
          })
          wx.setStorageSync('schoolId', nearest.id);
          wx.setStorageSync('mallStatus', nearest.buy_status);
          wx.setStorageSync('cityId', nearest.city_id);
          wx.setStorageSync('currentSchool', that.data.locate);
          wx.setStorageSync('provinceId', nearest.province_id);
        }
      }
    })
  },

  // 导航切换
  navChange:function(e){
    let index = e.currentTarget.dataset.index;
    let url = e.currentTarget.dataset.url;
    let that = this;

    if ( index!= that.data.currentPage){
      if(index==1){
        wx.reLaunch({
          url: url + '?locate=' + that.data.locate
        })
      }else{
        let pageUrl = url + '/#/index?dev=1&token=' + wx.getStorageSync('token') + '&openid=' + wx.getStorageSync('userInfo').openid + '&address=' + that.data.locate+'&school_id=' + wx.getStorageSync('schoolId') + '&longitude=' + wx.getStorageSync('longitude') + '&latitude=' + wx.getStorageSync('latitude');
        wx.navigateTo({
          url: '/pages/apply/web_page?url=' + encodeURIComponent(pageUrl)
        })
      }
    }
  },

  //获取banner
  getBanner: function () {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/sideshow/banner/get',
      data: {
        type: 2,
        token: wx.getStorageSync('token'),
        support: 1 //0: 全部 1: 小程序 2: 安卓 3: IOS
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (res.data.error == 0) {
          wx.hideLoading();
          that.setData({
            noNetwork: false,
            imgUrls: res.data.data
          })
          //判断前后距离
          switch (that.data.imgUrls.length){
            case 1: 
              that.setData({
                imgPreMargin:'65rpx',
                imgNextMargin: ''
              })
              break;
            case 2:
              that.setData({
                imgNextMargin: '150rpx'
              })
              break;
            default:
              that.setData({
                imgPreMargin: '75rpx', //banner前面露出的部分
                imgNextMargin: '75rpx'
              })
              break;
          }
        }
      }, fail(res) {
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
        that.setData({
          noNetwork: true
        })
      } 
    })
  },
  //banner活动页跳转
  activeNavgator: function (e) {
    let url = e.currentTarget.dataset.url;
    if (url.indexOf('https://x.boxinschool.com') > -1) {
      wx.navigateTo({
        url: 'active_page?url=' + encodeURIComponent(url),
      })
    }
    if (url == 'www.maohesharejudge.com') {
      wx.navigateTo({
        url: '/pages/mine/setting/recommend',
      })
    }   
  },

  //banner自定义小点
  swiperChange: function (e) {
    this.setData({
      currentIndex: e.detail.current
    })
    //判断前后距离
    if(this.data.currentIndex>=1){
      if (this.data.imgUrls.length == 2) {
        this.setData({
          imgPreMargin: '140rpx',
          imgNextMargin: '10rpx'
        })
      }
    }else{
      this.setData({
        imgPreMargin: '',
        imgNextMargin: '150rpx'
      })
    }
    if (this.data.imgUrls.length > 2) {
      this.setData({
        imgPreMargin: '75rpx', //banner前面露出的部分
        imgNextMargin: '75rpx'
      })
    }
  },

  // 申领盒子
  onApplyBox:function(){
    if (this.data.boxStatus == 0 || this.data.boxStatus == 5) {
      wx.navigateTo({
        url: "/pages/apply/apply_box",
      })
    } else {
      this.goSupplyPage();
    } 
  },

  //申请盒子手机号判断
  bindApplyBox: function (e) {
    let that = this;
    let userMsg = wx.getStorageSync('userInfo');

    if (userMsg.phone == '0' || userMsg.phone == 0) {//没有手机号
      if (e.detail.errMsg == 'getPhoneNumber:ok') {//同意手机号授权
        wx.request({
          url: App.data.globalAPI + '/users/weixin/decrypt',
          data: {
            token: wx.getStorageSync('token'),
            data: e.detail.encryptedData,
            iv: e.detail.iv
          },
          method: "POST",
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          success(res) {
            if (res.data.error == 0) {
              var myphone = JSON.parse(res.data.data).phoneNumber;

              let userInfo = wx.getStorageSync('userInfo');
              let allUserMsg = wx.getStorageSync('allUserMsg');
              userInfo.phone = myphone;
              allUserMsg.userinfo = userInfo;
              wx.setStorageSync('userInfo', userInfo);
              wx.setStorageSync('allUserMsg', allUserMsg);

              that.uploadUserMsg();
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'none',
                duration: 800
              })
            }
          }
        })
      }
    }

  },

  //提交用户手机
  uploadUserMsg: function () {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/users/user/bindphone',
      data: {
        token: wx.getStorageSync('token'),
        phone: wx.getStorageSync('userInfo').phone,
        validate_code: '0000',
        is_activity: 0
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success(res) {
        const arr = res.data;
        if (arr.error != 0) {
          wx.showToast({
            title: arr.msg,
            icon: 'none',
            duration: 800
          })
        }
        that.setData({
          hasPhone:true
        })

        if (Object.keys(arr.data).length > 0) { //以前有盒子
          wx.showToast({
            title: '信息同步成功',
            icon: 'success',
            duration: 1000
          })
          that.onLoad();
        } else {
          that.onApplyBox();
        }
      }, fail() {
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
      }
    })
  },


  // 扫码消费
  onScanBox:function(){
    const that = this;
    wx.scanCode({
      scanType: ['qrCode'],
      success(res) {
        let getUrl = res.result;
        if (getUrl.indexOf('promoteCode=') > -1) {//扫码的是高校端的申领盒子码
          if (wx.getStorageSync('userInfo').hostel_id != null) {
            wx.showToast({
              title: '您已经申领过盒子了',
              icon: 'none'
            })
          } else {
            wx.reLaunch({
              url: '/pages/apply/apply_box?q=' + encodeURIComponent(getUrl),
            })
          }
          return false;
        }

        // 扫码的是补货的确认订单
        if (getUrl.indexOf('type=supply') > -1 && getUrl.indexOf('supplyConfirm')>-1) {
          let str = getUrl.split('?')[1].split('&')[0];
          let orderNo = str.substring(9);
          if (wx.getStorageSync('userInfo').phone == '0' || wx.getStorageSync('userInfo').phone == null){
            wx.navigateTo({
              url: '/pages/mine/wxscan/supply_confirm?order_no=' + orderNo,
            })
          }else{
            wx.navigateTo({
              url: '/pages/mine/order/order_detail?order_no=' + orderNo
            })
          }
          return false;
        }

        // 扫码的是零食直购的确认订单
        if (getUrl.indexOf('type=snack') > -1 && getUrl.indexOf('snackConfirm') > -1) {
          let str = getUrl.split('?')[1].split('&')[0];
          let orderNum = str.substring(9);
          if (wx.getStorageSync('userInfo').phone == '0' || wx.getStorageSync('userInfo').phone == null) {
            wx.navigateTo({
              url: '/pages/mine/wxscan/cloud_confirm?order_no=' + orderNum,
            })
          } else {
            wx.request({
              url: App.data.globalAPI + '/order/mall/selforder',
              data: {
                token: wx.getStorageSync('token'),
                order_no: orderNum
              },
              method: 'POST',
              header: {
                'content-type': 'application/x-www-form-urlencoded' // 默认值
              },
              success(res) {
                if (res.data.error == 0) {
                  wx.navigateTo({
                    url: '/pages/mine/lingshi_order/lingshi_detail?order_no=' + orderNum
                  })
                } else {
                  wx.showToast({
                    title: res.data.msg,
                    icon: 'none',
                    duration: 1000
                  })
                }
              }
            })
          }
          return false;
        }

        let index = getUrl.indexOf('boxId=');
        if (index > -1) {
          var curPageArr = getCurrentPages();
          var page = curPageArr[curPageArr.length - 1];
          let userMsg = wx.getStorageSync('allUserMsg');
          let box_id = getUrl.substring(index + 6, getUrl.length);

          //游客判断是否可以绑定盒子管理员
          if (userMsg.userinfo.hostel_id == 'null' || userMsg.userinfo.hostel_id == null) {
            that.bindBoxManager(box_id);
            return false;
          }

          if (curPageArr[0].route.indexOf('/index') > -1) {//当前打开的是首页
            boxId = box_id;       
            that.getButtonStatus();
          } else {
            wx.redirectTo({
              url: '/pages/index/index?boxId=' + box_id,
            })
          }

        }
        else {
          wx.showToast({
            title: '二维码错误',
            icon: 'none'
          })
        }

      }
    })
  },
  //绑定盒子管理员
  bindBoxManager: function (box_id) {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/box/attr/getstatus', //接口地址
      data: {
        token: wx.getStorageSync('token'),
        box_id: box_id,
      },
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function (res) {
        if (res.data.error == 0) {
          if (res.data.data.master == 0 && res.data.data.is_apply) { //没有管理员且可以申请盒子
            wx.redirectTo({
              url: '/pages/apply/apply_box?boxId=' + box_id,
            })
          }else{
            boxId = box_id;
            that.getButtonStatus();
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  }, 

  //获取消费列表
  getBoxGoodsList: function () {
    wx.showLoading({
      title: '加载中',
    })
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/box/goods/list',
      data: {
        box_id: boxId,
        token: wx.getStorageSync('token')
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (wx.getStorageSync('firstxiaofei') == '') {
          that.setData({
            showGuideIntro: true
          })
        }
        wx.setStorageSync('firstxiaofei', true);
        if (res.data.error == 0) {
          //为每个商品添加购买数量字段
          let list = res.data.data;
          for (var k = 0; k < list.length; k++) {
            list[k].buy_num = 0;
          }
          that.setData({
            goodsList: list,
          })
          showList = list;
          if(that.data.goodsList.length==0){
            that.setData({
              noGoods: true
            })
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 800
          })
        }
        wx.hideLoading();
      }
    })
  },

  //重新加载页面
  refreshPage: function () {
    wx.reLaunch({
      url: '/pages/index/index',
    })
  },

  // 返回我的盒子
  goMyBox:function(){
    let allMsg = wx.getStorageSync('allUserMsg');
    boxId = allMsg.box.box_id == null ? '' : allMsg.box.box_id;
    this.clearShopCart();
    this.getButtonStatus();
  },

  // 数量加事件
  onAddHandle: function (e) {
    let gIndex = e.currentTarget.dataset.index;
    let list = this.data.goodsList;
    let goodsMsg = e.currentTarget.dataset.msg;
    let currentCart = this.data.shoppingCart;

    if (parseInt(list[gIndex].buy_num) >= parseInt(goodsMsg.number)) {
      wx.showToast({
        title: '库存已达上限',
        icon: 'none',
        duration: 800
      })
      return false;
    }
    if (currentCart.length > 0) {//购物车中有商品时
      let flag = false;//判断是否加入过购物车
      for (var i = 0; i < currentCart.length; i++) {
        if (goodsMsg.goods_id == currentCart[i].goods_id) {
          currentCart[i].buy_num++;
          flag = true;
        }
      }
      if (!flag) {
        goodsMsg.buy_num++;
        currentCart.unshift(goodsMsg)
      }
    } else {
      goodsMsg.buy_num++;
      currentCart.unshift(goodsMsg)
    }

    list[gIndex].buy_num++;
    this.setData({
      shoppingCart: currentCart,
      goodsList: list
    })
    this.amountShopcart();//计算商品数量和价格
  },

  // 数量减事件
  onSubHandle: function (e) {
    let gIndex = e.currentTarget.dataset.index;
    let currentList = this.data.goodsList;
    let goodsMsg = e.currentTarget.dataset.msg;
    let currentCart = this.data.shoppingCart;

    for (var i = 0; i < currentCart.length; i++) {
      if (goodsMsg.goods_id == currentCart[i].goods_id) {
        currentCart[i].buy_num--;
        if (currentCart[i].buy_num == 0) {
          currentCart.splice(i, 1)
        }
      }
    }

    currentList[gIndex].buy_num--;
    this.setData({
      shoppingCart: currentCart,
      goodsList: currentList
    })
    this.amountShopcart();//计算商品数量和价格
  },

  // 计算购物车商品数量和价格
  amountShopcart: function () {
    let list = this.data.shoppingCart;
    let number = 0;
    let money = 0;
    let activeSave = 0; // 活动优惠节省
    let vipSave = 0;  //vip优惠了多少钱
    let realMoney = 0; //订单的实际价格

    for (var i = 0; i < list.length; i++) {
      number += list[i].buy_num;
      money = parseFloat(money) + parseFloat(list[i].price) * parseInt(list[i].buy_num);//原价

      if (list[i].vip_status == 0) { //商品是vip
        vipSave = parseFloat(vipSave) + parseFloat(list[i].price - list[i].vip_price).toFixed(2) * parseInt(list[i].buy_num);
      } else {
        if (list[i].activity_status == 0) {//商品是活动商品
          activeSave = parseFloat(activeSave) + parseFloat(list[i].price - list[i].activity_price).toFixed(2) * parseInt(list[i].buy_num);
        }
      }
    }

    if (this.data.userIsvip) { //用户是vip
      realMoney = parseFloat(money - activeSave - vipSave).toFixed(2);
    } else {
      realMoney = parseFloat(money - activeSave).toFixed(2);
    }

    this.setData({
      totalNum: number,
      totalMoney: realMoney,
      originTotal: parseFloat(money).toFixed(2),
      vipSave: parseFloat(vipSave).toFixed(2), //vip优惠价格
      activeSave: parseFloat(activeSave).toFixed(2),
      totalSave: parseFloat(parseFloat(money).toFixed(2) - realMoney).toFixed(2)
    })
  },

  // 显示购物车列表
  showShopCart: function () {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/sideshow/banner/get',
      data: {
        token: wx.getStorageSync('token'),
        type: '-2',
        support: 1
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (res.data.error == 0) {
          if (res.data.data[0] != undefined) {
            that.setData({
              cartActiveMsg: res.data.data[0].content,
            })
          }   
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 800
          })
        }
        wx.hideLoading();
      }
    })
    that.setData({
      hoverAlert: true,
    })
  },

  // 关闭弹窗
  showPayModal: function () {
    let list = this.data.shoppingCart;
    for (var i = 0; i < list.length; i++) {//数量为0，关闭时从列表移除
      if (list[i].buy_num == 0) {
        list.splice(i, 1);
        i--;
      }
    }
    this.setData({
      hoverAlert: false,
      shoppingCart: list
    })
  },
  stopHandle: function () {
    return false;
  },

  //清空购物车
  clearShopCart: function () {
    let list = this.data.goodsList;
    for (var i = 0; i < list.length; i++) {
      list[i].buy_num = 0;
    }
    this.setData({
      shoppingCart: [],
      hoverAlert: false,
      goodsList: list
    })
    this.amountShopcart();
  },

  // 购物车中商品数量减少
  onSubCartHandle: function (e) {
    let sList = this.data.shoppingCart;
    let cIndex = e.currentTarget.dataset.cindex;
    let cId = e.currentTarget.dataset.id;
    let list = this.data.goodsList;

    if (sList[cIndex].buy_num > 0) {//商品列表中对应购物车商品数量变化
      for (var j = 0; j < list.length; j++) {
        if (cId == list[j].goods_id) {
          list[j].buy_num--;
          sList[cIndex].buy_num--;
          if (sList[cIndex].buy_num == 0) {
            sList.splice(cIndex, 1);
          }
        }
      }

    }

    this.setData({
      shoppingCart: sList,
      goodsList: list
    })
    this.amountShopcart();
    if (parseInt(this.data.totalNum) == 0) { //购物车列表为空时关闭弹窗
      this.setData({
        hoverAlert: false
      })
    }
  },
  //购物车商品增加
  onAddCartHandle: function (e) {
    let sList = this.data.shoppingCart;
    let cIndex = e.currentTarget.dataset.cindex;
    let cId = e.currentTarget.dataset.id;
    let max = e.currentTarget.dataset.max;
    let list = this.data.goodsList;
    if (sList[cIndex].buy_num >= max) {
      wx.showToast({
        title: '库存已达上限',
        icon: 'none',
        duration: 600
      })
    }
    else {
      sList[cIndex].buy_num++;
      for (var j = 0; j < list.length; j++) {
        if (cId == list[j].goods_id) {
          list[j].buy_num++;
        }
      }
      this.setData({
        shoppingCart: sList,
        goodsList: list
      })
      this.amountShopcart();
    }
  },

  // 去支付
  goPaymentBlock: function () {
    this.setData({
      hoverAlert: false,
      paymentBlock: true,
      orderMoney: parseFloat(this.data.totalMoney).toFixed(2)
    })
    this.showPayModal();
    wx.navigateTo({
      url: '/pages/index/index_order?ordermsg=' + JSON.stringify(this.data.shoppingCart) + '&total=' + this.data.totalMoney + '&origin=' + this.data.originTotal + '&vipSave=' + this.data.vipSave + ' &activeSave=' + this.data.activeSave + '&boxId=' + boxId
    })
  },

  // 关闭新人活动弹窗
  closeActiveAlert:function(){
    this.setData({
      newPersonActive: false,
      everyLogin:  true,
    })
  },

  // 关闭每日登录弹窗
  closeActiveAlert2: function () {
    this.setData({
      everyLogin: false
    })
  },

  //列表分类筛选
  choseShowType:function(e){
    let index = parseInt(e.currentTarget.dataset.index);
    let goodslist = [];
    switch (index){
      case 0:
        goodslist = showList
        break;
      case 1: 
        showList.forEach((item)=>{
          if (item.activity_status==0){
            goodslist.push(item)
          }
        })
        break;
      case 2:
        showList.forEach((item) => {
          if (item.vip_status == 0) {
            goodslist.push(item)
          }
        })
        break;
      default:
    }
    if (goodslist.length>0){
      this.setData({
        goodsList: goodslist,
        currentType: index
      })
    }else{
      wx.showToast({
        title: '分类下商品为空',
        icon:'none'
      })
    }
  },

  //获取补货广告提示
  supplyAdMsg: function(){
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/sideshow/banner/get',
      data: {
        token: wx.getStorageSync('token'),
        type: '-1', //消费页补货
        support: 1
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (res.data.error == 0) {
          if (res.data.data[0] != undefined){
            that.setData({
              managerTip: res.data.data[0].content,
            })
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 800
          })
        }
        wx.hideLoading();
      }
    })
  },

  //更新版本信息
  updateVersion: function () {
    const updateManager = wx.getUpdateManager();
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      console.log(res.hasUpdate)
    })
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否马上重启小程序？',
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate();
          }
        }
      })
    })
  },

  // 联系客服
  onCallServer:function(){
    wx.makePhoneCall({
      phoneNumber: '18131109842' 
    })
  },

  // 去补货页面
  goSupplyPage:function(){
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/mall/goods/getyunbuystatus', //接口地址
      data: {
        token: wx.getStorageSync('token'),
        school_id: wx.getStorageSync('userInfo').school_id
      },
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function (res) {
        if (res.data.error == 0) {
          if (res.data.data.supply_status==1){
            if (!canGOSupply){
              wx.navigateTo({
                url: '/pages/index/replenishment/buhuo',
              })
              canGOSupply = true
            }
            
          }else{
            wx.showToast({
              title: '补货商城暂未开启',
              icon:'none'
            })
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }, fail(res) {
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
      },
    })
  },

  // 新人活动的广告位
  newPersonImg:function(){
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/sideshow/banner/get', //接口地址
      data: {
        token: wx.getStorageSync('token'),
        type: 8 , //新用户弹窗
        support: 1
      },
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function (res) {
        if (res.data.error == 0) {
          that.setData({
            newPersonAd: res.data.data[0].img
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }, fail(res) {
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
      },
    })
  },

  // 每日登录提醒
  everyLoginHandle:function(){
    let that = this;
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth()+1;
    let day = date.getDate();
    let current = year+'-'+month+'-'+day;
    
    if (current != wx.getStorageSync('today')){
      wx.setStorageSync('today', current)
      wx.request({
        url: App.data.globalAPI + '/sideshow/banner/get', //接口地址
        data: {
          token: wx.getStorageSync('token'),
          type: 9, //每日登录
          support: 1
        },
        header: {
          'content-type': 'application/json' //默认值
        },
        success: function (res) {
          if (res.data.error == 0) {
            that.setData({
              everyLogin: that.data.newPersonActive?false:true,
              everyLoginImg: res.data.data[0].img
              // everyLoginImg: '../../images/alert_img.png'
            })
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        }, fail(res) {
          wx.showModal({
            title: '提示',
            content: '网络异常，请稍后重试！',
            showCancel: false,
            success(res) {
            }
          })
        },
      })
    }else{
      that.setData({
        everyLogin: false
      })
    }
  },

  // 隐藏首次引导
  hideFirstIntro: function (e) {
    let column = e.currentTarget.dataset.guide;
    if (column =='more'){ //更多蒙层
      this.setData({
        moreGuideAlert: false
      })
    }else{
      this.setData({
        showGuideIntro: false
      })
    } 
  },

  //确认收货
  onSendHandle:function(){
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/order/users/confirm',
      data: {
        token: wx.getStorageSync('token'),
        order_no: wx.getStorageSync('allUserMsg').first_supply.order_no
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        if (res.data.error == 0) {
          wx.showToast({
            title: '确认收货成功！',
          })
          that.setData({
            showConfirm:false
          })
          setTimeout(function () {
            that.getTokenLogin();
          }, 800)  
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 800
          })
        }
      }, fail(res) {
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
      }
    })
  },

  // 关闭确认送达
  closeSendWin: function () {
    this.setData({
      showConfirm: !this.data.showConfirm
    })
  },


})